function ServiceModel(stompClient) {
	var self = this;

	self.stompClient = stompClient;
	self.friends = ko.observableArray();
	self.organizations = ko.observableArray();
	self.username = ko.observable();
	self.conversation = ko.observable(new ImConversationModel(stompClient,
			this.username));
	self.notifications = ko.observableArray();
	self.csrfToken = ko.computed(function() {
		return JSON.parse($.ajax({
			type : 'GET',
			url : 'csrf',
			dataType : 'json',
			success : function() {
			},
			data : {},
			async : false
		}).responseText);
	}, this);

	self.connect = function() {
		var csrf = self.csrfToken();
		var headers = {};
		headers[csrf.headerName] = csrf.token;
		stompClient.connect(headers, function(frame) {

			console.log('Connected ' + frame);
			self.username(frame.headers['user-name']);

			// 注册错误时间监听
			stompClient.subscribe("/user/queue/errors", function(message) {
				self.pushNotification("Error " + message.body);
			});

			// 查询好友
			stompClient.subscribe("/app/friends", function(message) {
				var friends = JSON.parse(message.body);

				for (var i = 0; i < friends.length; i++) {
					var friend = friends[i];
					self.friendsInit(new ImFriend({
						username : friend.username,
						online : friend.online,
						messageCount : friend.messageCount
					}));
				}
			});

			// 查询服务商
			stompClient.subscribe("/app/organizations", function(message) {
				var organizations = JSON.parse(message.body);

				for (var i = 0; i < organizations.length; i++) {
					var organization = organizations[i];
					self.organizationsInit(new ImFriend({
						username : organization.username,
						online : organization.online,
						messageCount : organization.messageCount
					}));
				}
			});

			// 注册好友登录监听
			stompClient.subscribe("/topic/users/signin", function(message) {
				var users = JSON.parse(message.body);

				for (var i = 0; i < users.length; i++) {
					self.userSignin(users[i]);
				}
			});

			// 注册用户登出监听
			stompClient.subscribe("/topic/users/signout", function(message) {
				var users = JSON.parse(message.body);

				for (var i = 0; i < users.length; i++) {
					self.userSignout(users[i]);
				}
			});

			// 注册消息通道
			var destination = "/user/queue/messages"; // "/queue/*"
			stompClient.subscribe(destination, function(message) {
				var msg = JSON.parse(message.body);
				// 如果消息源就是目前正在聊天的人，显示聊天数据
				if (self.conversation().to().username == msg.from
						|| self.username() == msg.from) {
					self.conversation().receiveMessage(msg);
				} else {
					self.freshMessageCount({
						username : msg.from
					});
				}
			});
		}, function(error) {
			self.pushNotification(error);
			console.log("STOMP protocol error " + error);
		});
	};

	self.pushNotification = function(text) {
		self.notifications.push({
			notification : text
		});
		if (self.notifications().length > 5) {
			self.notifications.shift();
		}
	};

	self.logout = function() {
		stompClient.disconnect();
		window.location.href = "../logout.html";
	};

	self.friendsInit = function(imfriend) {
		self.friends.push(imfriend);
	};

	self.organizationsInit = function(imfriend) {
		self.organizations.push(imfriend);
	};

	self.userSignin = function(user) {
		self.friends().forEach(function(item) {
			if (item.username == user) {
				item.online(true);
			}
		});
		self.organizations().forEach(function(item) {
			if (item.username == user) {
				item.online(true);
			}
		});
	};

	self.userSignout = function(user) {
		self.friends().forEach(function(item) {
			if (item.username == user) {
				item.online(false);
			}
		});
		self.organizations().forEach(function(item) {
			if (item.username == user) {
				item.online(false);
			}
		});
	};

	self.freshMessageCount = function(user) {
		self.friends().forEach(function(item) {
			if (item.username == user.username) {
				item.messageCount(item.messageCount() + 1);
			}
		});
		self.organizations().forEach(function(item) {
			if (item.username == user.username) {
				item.messageCount(item.messageCount() + 1);
			}
		});
	};
}

function ImFriend(data) {
	var self = this;

	self.username = data.username;
	self.online = ko.observable(data.online);
	self.messageCount = ko.observable(data.messageCount);
	self.profitStatus = ko.computed(function() {
		return this.online() ? "active" : "";
	}, self);
}

function ImConversationModel(stompClient, from) {
	var self = this;
	self.stompClient = stompClient;
	self.from = from;
	self.to = ko.observable(new ImFriend('null'));
	self.draft = ko.observable('')
	// self.lastChatter = ko.observable('');

	self.messages = ko.observableArray();

	self.messages.subscribe(function(v) {
		var elem = $('#chat');
		elem.scrollTop(elem[0].scrollHeight);
	});

	self.receiveMessage = function(message) {

		self.messages.pop();
		self.messages.push(new ImModel(message));
		// 解决div的滚动条的问题。在ko数据刷新的时候，触发subscribe方法和刷新页面的顺序不定，导致有时候刷先触发的subscribe方法，后刷新的页面，后添加的元素会在Scroll下面出现，并不会调整Scroll的高度
		message.message = "  ";
		self.messages.push(new ImModel(message));
		// self.lastChatter(message.from);
		if (message.from != self.from()) {
			// 如果不是自己发送的信息，不发送收到信息的反馈
			var destination = "/app/rm"; // /queue/messages-user1
			stompClient.send(destination, {}, JSON.stringify(message));
		}

	};

	self.chat = function(to) {
		self.to(to);
		self.draft('');
		// self.lastChatter('');
		self.messages.removeAll();

		// 查询历史信息
		stompClient.subscribe("/app/history/" + self.to().username, function(
				message) {
			var msgs = JSON.parse(message.body);

			for (var i = 0; i < msgs.length; i++) {
				self.receiveMessage(msgs[i]);
			}
			self.to().messageCount(0);
		});
		// $('#trade-dialog').modal();
	}

	self.send = function() {
		var data = {
			"created" : new Date(),
			"from" : self.from(),
			"to" : self.to().username,
			"message" : self.draft()
		};
		var destination = "/app/im"; // /queue/messages-user1
		stompClient.send(destination, {}, JSON.stringify(data));
		self.draft('');
	};

	self.layoutTemplate = function(index) {

		var from = (self.messages())[index()].from;
		var preFrom = "";
		if (index() > 0) {
			preFrom = (self.messages())[index() - 1].from;
		}

		if (from == self.from()) {
			if (preFrom == from) {
				return "right-continue";
			}
			return "right-begin";
		} else {
			if (preFrom == from) {
				return "left-continue";
			} else {
				return "left-begin";
			}
		}
	}
};

function ImModel(data) {
	var self = this;

	self.created = new Date(data.created);
	self.to = data.to;
	self.message = data.message;
	self.from = data.from;
	self.timeFormat = ko.computed(function() {
		return self.created.getFullYear() + "/" + (self.created.getMonth() + 1)
				+ "/" + self.created.getDay() + " " + self.created.getHours()
				+ ":" + self.created.getMinutes() + ":"
				+ self.created.getSeconds();
	});
	// self.layoutTemplate = ko.computed(function(chatTo) {
	// return self.from == chatTo ? "chat-to" : "chat-from";
	// });
};

